<template>
  <div class="category-manage-container">
    <div class="top-operation">
      <!-- 分类表格 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="分类名称">
          <el-input v-model="searchForm.categoryName" placeholder="请输入分类名称" clearable style="width: 240px;"></el-input>
        </el-form-item>
        <!-- 功能表格 -->
        <el-form-item>
          <el-button type="primary" @click="getCategoryList(1)">搜索</el-button>
          <el-button type="success" @click="openAddModal">添加分类</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 分类列表 -->
    <el-table v-loading="listLoading" :data="categoryList" border stripe style="width: 100%; margin-top: 15px;">
      <el-table-column prop="name" label="分类名称" min-width=""></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="" align="center"></el-table-column>
      <el-table-column label="操作" width="100px" align="center">
        <template slot-scope="scope">
          <el-button type="danger" size="small" color="#f56c6c" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="pageParams.current" :page-sizes="[10, 20, 30]" :page-size="pageParams.size"
      layout="total, sizes, prev, pager, next, jumper" :total="totalCount"
      style="margin-top: 20px; text-align: right;"></el-pagination>

    <!-- 添加分类模态框 -->
    <el-dialog title="添加分类" :visible.sync="addModalVisible" width="400px" :before-close="closeAddModal">
      <el-form :model="addForm" label-width="80px" class="form-container">
        <el-form-item label="分类名称" required
          :rules="[{ required: true, message: '请输入分类名称', trigger: 'blur' }, { max: 10, message: '最多输入10个字符', trigger: 'blur' }]">
          <el-input v-model="addForm.name" placeholder="请输入分类名称" style="width: 260px;"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAddModal">取消</el-button>
        <el-button type="primary" @click="submitAdd">确认添加</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类模态框 -->
    <el-dialog title="编辑分类" :visible.sync="editModalVisible" width="400px" :before-close="closeEditModal">
      <el-form :model="editForm" label-width="80px" class="form-container">
        <el-form-item label="分类名称" required
          :rules="[{ required: true, message: '请输入分类名称', trigger: 'blur' }, { max: 10, message: '最多输入10个字符', trigger: 'blur' }]">
          <el-input v-model="editForm.name" placeholder="请输入分类名称" style="width: 260px;"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeEditModal">取消</el-button>
        <el-button type="primary" @click="submitEdit">确认修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CategoryManage',
  data() {
    return {
      // 列表相关
      categoryList: [],
      listLoading: false,
      totalCount: 0,
      pageParams: { current: 1, size: 10 },
      searchForm: { categoryName: '' },

      // 添加模态框相关
      addModalVisible: false,
      addForm: { name: '' },

      // 编辑模态框相关
      editModalVisible: false,
      editForm: { id: '', name: '' }
    }
  },
  mounted() {
    this.getCategoryList();
  },
  methods: {
    // 获取分类列表
    async getCategoryList() {
      this.listLoading = true;
      try {
        const res = await this.$axios.post(
          '/api/admin/category/list',
          {
            ...this.pageParams,
            categoryName: this.searchForm.categoryName
          }
        );
        if (res.status ==200) {
          console.log(res);
          this.categoryList = res.data.data;
          this.totalCount = res.data.total;
        } else {
          this.$message.error(`获取分类列表失败：${res.data.message || '未知错误'}`);
        }
      } catch (err) {
        this.$message.error('接口请求异常，请稍后重试');
        console.error('CategoryList request error:', err);
      } finally {
        this.listLoading = false;
      }
    },

    // 打开添加分类模态框
    openAddModal() {
      this.addModalVisible = true;
      this.addForm = { name: '' };
    },

    // 关闭添加分类模态框
    closeAddModal() {
      this.addModalVisible = false;
      this.addForm = { name: '' };
    },

    // 提交添加分类
    async submitAdd() {
      try {
        const res = await this.$axios.post(
          '/api/admin/category/add',
          this.addForm
        );
        if (res.data.success) {
          console.log(res);
          this.$message.success('分类添加成功');
          this.closeAddModal();
          this.getCategoryList();
        } else {
          this.$message.error(`添加失败：${res.data.message || '未知错误'}`);
        }
      } catch (err) {
        this.$message.error('添加分类接口请求异常，请稍后重试');
        console.error('CategoryAdd request error:', err);
      }
    },

    // 打开编辑分类模态框
    openEditModal(row) {
      this.editModalVisible = true;
      this.editForm = { ...row };
    },

    // 关闭编辑分类模态框
    closeEditModal() {
      this.editModalVisible = false;
      this.editForm = { id: '', name: '' };
    },

    // 提交编辑分类
    async submitEdit() {
      try {
        const res = await this.$axios.post(
          '/api/admin/category/update',
          this.editForm
        );
        if (res.data.success) {
          console.log("分类");
          
          this.$message.success('分类修改成功');
          this.closeEditModal();
          this.getCategoryList();
        } else {
          this.$message.error(`修改失败：${res.data.message || '未知错误'}`);
        }
      } catch (err) {
        this.$message.error('编辑分类接口请求异常，请稍后重试');
        console.error('CategoryEdit request error:', err);
      }
    },

    // 删除分类
    async handleDelete(categoryId) {
      try {
        await this.$confirm('确定要删除该分类吗？删除后不可恢复！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        const res = await this.$axios.post(
          '/api/admin/category/delete',
          { categoryId }
        );
        if (res.status ==200) {
          console.log("分类删除成功",res);
          this.$message.success('分类删除成功');
          this.getCategoryList();
        } else {
          this.$message.error(`删除失败：${res.data.message || '未知错误'}`);
        }
      } catch (err) {
        console.error('CategoryDelete request error:', err);
        this.$message.info('已取消删除');
      }
    },

    // 每页条数改变触发
    handleSizeChange(val) {
      this.pageParams.size = val;
      this.pageParams.current = 1;
      this.getCategoryList();
    },

    // 当前页改变触发
    handleCurrentChange(val) {
      this.pageParams.current = val;
      this.getCategoryList();
    }
  }
}
</script>

<style scoped>
.category-manage-container {
  padding: 20px;
}

.top-operation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.form-container {
  padding: 10px 0;
}
</style>